#!/usr/bin/env python
#coding:utf-8

import urllib
import urllib2
from sgmllib import SGMLParser

class URLLister(SGMLParser):
    def reset(slef):
        SGMLParser.reset(self)
        self.result = []
        self.open = False

    def start_div(self, attrs):
        id = [v for k, v in attrs if k=='id']
        if "result_box" in id:
            self.open = True

    def handle_data(self, text):
        if self.open:
            self.result.append(text)
            self.open = False

while True:
    text = raw_input("请输入要翻译的英文（退出输入q）：")
    if text == 'q':
        break
    values = {"hl":"zh-CN",
              "ie":"utf-8",
              "text":text,
              "langpair":"en|zh-CN"
              }
    url = 'http://translate.google.cn/translate_t'
    data = urllib.urlencode(values)
    req = urllib2.Request(url, data)
    #print req
    req.add_header('User-Angen',"Mozilla/5.0+(compatible;+Googlebot/2.1;++http://www.google.com/bot.html)")
    response = urllib2.urlopen(req)
    parser = URLLister()
    parser.feed(response.read())
    parser.close()
    print "翻译的结果是："
    for i in parser.result:
        i = unicode(i, 'utf-8').encode('gbk')
        print i
